import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { getAllTopList } from '../service/rank';
import { getRanking } from '@/service';
import { RootState } from '@/store';

interface IState {
  topList: any[];
  currentRank: any;
  currentId: number;
  rankList: any[];
}
const initialState: IState = {
  topList: [],
  currentRank: {},
  rankList: [],
  currentId: -1,
};

export const fetchTopList = createAsyncThunk('rank/TopList', async () => {
  const response: any = await getAllTopList();
  // console.log(response);
  return response.list;
});

export const fetchRankDetail = createAsyncThunk('rank/Detail', async (id: number, { dispatch, getState }) => {
  const nowList = (getState() as RootState).rank.rankList.slice();
  let findIndex = nowList.findIndex((val) => val.id === id);
  let response: any;
  if (findIndex === -1) {
    let res: any = await getRanking(id);
    response = res.playlist;
    nowList.push(response);
    dispatch(setRankList(nowList));
    dispatch(setCurrentId(nowList.length - 1));
  } else {
    response = nowList[findIndex];
  }
  return response;
});

const RankSlice = createSlice({
  initialState,
  name: 'rank',
  reducers: {
    setCurrentRank: (state, { payload }: PayloadAction<any>) => {
      state.currentRank = payload;
    },
    setRankList: (state, { payload }: PayloadAction<any>) => {
      state.rankList = payload;
    },
    setCurrentId: (state, { payload }: PayloadAction<number>) => {
      state.currentId = payload;
    },
  },
  extraReducers: (builder) => {
    // 获取榜单列表
    // 处理请求开始状态
    builder.addCase(fetchTopList.pending, (state) => {
      // console.log('pending');
    });
    // 处理请求成功状态
    builder.addCase(fetchTopList.fulfilled, (state, action) => {
      state.topList = action.payload;
    });
    // 处理请求失败状态
    builder.addCase(fetchTopList.rejected, (state, action) => {
      // console.log('rejected');
    });

    // 获取榜单详情
    // 处理请求开始状态
    builder.addCase(fetchRankDetail.pending, (state) => {
      // console.log('pending');
    });
    // 处理请求成功状态
    builder.addCase(fetchRankDetail.fulfilled, (state, action) => {
      state.currentRank = action.payload;
    });
    // 处理请求失败状态
    builder.addCase(fetchRankDetail.rejected, (state, action) => {
      // console.log('rejected');
    });
  },
});

export const { setCurrentRank, setRankList, setCurrentId } = RankSlice.actions;

export default RankSlice.reducer;
